package advanced进阶;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 用的广泛成度：Callable > Runnable > Thread
 * 因为在使用多线程中，大部分需要返回结果，然后进行处理
 *
 */

/*
//不使用Callable方法
class Result{
    private int sum;

    public int getSum() {
        return sum;
    }

    public void setSum(int sum) {
        this.sum = sum;
    }
}
public class Callable接口 {

    public static void main(String[] args) throws InterruptedException {
        Result result = new Result();
        Thread thread = new Thread(()->{
           int sum = 0;
            for (int i = 0; i < 1000; i++) {
                sum += i;
            }
            result.setSum(sum);
        });
        thread.start();
        //main线程需要获取sum,通过共享变量的方式来获取
        thread.join();
        System.out.println(result.getSum());
    }
}

 */

//使用Callable方法
    //FutureTask是一个异步运算的任务，也是Runnable的子类，所以可以通过new Thread（Runnable runnable）这个构造函数来启动线程
    //创建线程的方法中实现Runnable和实现Callable本质上是一个，Callable需要交给FutureTask，FutureTask是Runnable的一个实现

public class Callable接口 {
    /*
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable callable = () -> {
            int sum = 0;
            for (int i = 0; i < 1000; i++) {
                sum += i;
            }
            return sum;
        };
        FutureTask<Integer> task = new FutureTask<>(callable);
        new Thread(task).start();
        int sum = task.get();
        System.out.println(sum);
    }

     */


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable callable = new Callable() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i < 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };
        //使用FutureTask把Callable包装，交给线程执行
        FutureTask<Integer> task = new FutureTask(callable);
        new Thread(task).start();
        int sum = task.get();//得到结果
        System.out.println(sum);
    }
}
